package com.quanfaqiang.demo1.aop;

import com.alibaba.fastjson.JSONObject;
import com.quanfaqiang.demo1.mapper.OperateLogMapper;
import com.quanfaqiang.demo1.pojo.OperateLog;
import com.quanfaqiang.demo1.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class DeleteLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.quanfaqiang.demo1.anno.DeleteLog))")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username=null;
        if (map!=null){
            username= (String) map.get("username");
        }
        LocalDateTime now = LocalDateTime.now();//操作时间
        String path = DeleteLogAspect.class.getClassLoader().getResource("").getPath();
        System.out.println(path+"------------------------------");
        String operateName="";
        String className = joinPoint.getTarget().getClass().getName();//操作类名
        if (className.equals("com.quanfaqiang.demo1.controller.UserController")){
            operateName="用户";
        } else if (className.equals("com.quanfaqiang.demo1.controller.FurnitureController")) {
            operateName="家具";
        }else if (className.equals("com.quanfaqiang.demo1.controller.FurnituretypesController")) {
            operateName="家具类型";
        }else if (className.equals("com.quanfaqiang.demo1.controller.NoticeController")) {
            operateName="公告";
        }else if (className.equals("com.quanfaqiang.demo1.controller.QuyutypesController")) {
            operateName="区域类型";
        }else if (className.equals("com.quanfaqiang.demo1.controller.StatetypesController")) {
            operateName="状态类型";
        }else if (className.equals("com.quanfaqiang.demo1.controller.TaskController")) {
            operateName="任务";
        }else if (className.equals("com.quanfaqiang.demo1.controller.OperateLogController")) {
            operateName="操作记录";
        }
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);//操作方法参数
        Object result = joinPoint.proceed();//调用原始目标方法运行
        String returnValue = JSONObject.toJSONString(result);//方法返回值
        OperateLog operateLog1 = new OperateLog(null,username,now,"删除",operateName,methodParams,returnValue);
        operateLogMapper.insert(operateLog1);
        log.info("AOP记录操作日记：{}",operateLog1);
        return result;

    }
}
